package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordSignal;
import com.iqiyi.pps.epg.api.model.web.record.TRecordSignalPage;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordCol;
import com.iqiyi.pps.epg.core.model.record.RecordSignal;
import com.iqiyi.pps.epg.core.utils.SqlUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.type.StringType;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
@Component
public class RecordSignalDao extends BaseDao<RecordSignal> {


    public TRecordSignalPage findSignalPage(TPage page, TFilter filter) {
        String tempPattern = "${PARAMS}";
        String resultPattern = "recordSignal.id,recordSignal.signal_name,recordSignal.signal_address,recordSignal.priority,recordSignal.server_cluster,recordSignal.op_user,recordSignal.create_time,recordSignal.status ";
        String hql = "select " + tempPattern + " from record_signal recordSignal where recordSignal.status <> -1 ";
        String totalPattern = "COUNT(*) as total";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String original = page.getOrderBy();
        page.setOrderBy(rebuildOrderBy(original, "recordSignal"));
        Page<TRecordSignalPage> dbPage = TransUtil.buildPage(page);
        String sql = SqlUtil.buildWithPropertyFilter(hql, filterList);
        boolean skipQuery = false;
        if (dbPage.isAutoCount()) {
            logger.debug("[build sql totalPattern]" + sql.replace(tempPattern, totalPattern));
            String totalCount = getSession().createSQLQuery(sql.replace(tempPattern, totalPattern))
                    .addScalar("total", new StringType()).list().get(0).toString();

            page.setTotalCount(Long.valueOf(totalCount));
            if (page.getTotalCount() == 0) {
                skipQuery = true;
                logger.debug("[skip query  case total is zero ]");
            }
        }

        List<TRecordSignal> dataList = null;
        try {
            dataList = new ArrayList<>();
            if (!skipQuery) {
                sql = SqlUtil.buildAppendPage(dbPage, sql);
                sql = SqlUtil.buildAppendPageLimit(dbPage, sql);
                logger.debug("[build sql resultPattern ]" + sql.replace(tempPattern, resultPattern));
                String replaceSql = sql.replace(tempPattern, resultPattern);
                List result = getSession().createSQLQuery(replaceSql).list();
                TRecordSignal singleData = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Object single : result) {
                    Object[] obj = (Object[]) single;
                    singleData = new TRecordSignal();
                    singleData.setId(Long.valueOf("" + obj[0]));
                    singleData.setSignalName(obj[1] == null ? null :""+obj[1]);
                    singleData.setSignalAddress(obj[2] == null ? null :""+obj[2]);
                    singleData.setPriority(Integer.valueOf(""+obj[3]));
                    singleData.setServerCluster(obj[4] == null ? null :""+obj[4]);
                    singleData.setOpUser(obj[5] == null ? null :""+obj[5]);
                    singleData.setCreateTime(sdf.format(obj[6]));
                    singleData.setStatus(Integer.valueOf("" + obj[7]));
                    dataList.add(singleData);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("findSignalPage[exception]{}", e);
        }
        TRecordSignalPage libraryPage = new TRecordSignalPage();
        page.setOrderBy(original);
        libraryPage.setTPage(page);
        libraryPage.setResult(dataList);
        return libraryPage;
    }

    private String rebuildOrderBy(String original, String aliasName) {
        String[] params = original.split(",");
        StringBuilder sBuilder = new StringBuilder();
        for (String param : params) {
            sBuilder.append(aliasName + "." + param);
            sBuilder.append(",");
        }
        if (sBuilder.length() > 0) {
            sBuilder.deleteCharAt(sBuilder.length() - 1);
        }
        return sBuilder.toString();
    }

}
